package com.luckdraw.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.annotation.InjectName;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Xmls;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

import com.luckdraw.service.ActivityService;
import com.luckdraw.service.TenpayService;


@At("/payment")
@IocBean
@InjectName
public class PayMobule {
	
	@Inject
	private TenpayService tenpayService;
	
	@Inject
	ActivityService luckDrawService;

	private static final Log tenpaylog = Logs.getLog("PayMobule");
	
	/**
	 * 微信支付回调
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@At("/tenpayNotify")
	@Ok("void")
	public void tenpayNotify(HttpServletRequest request,HttpServletResponse response) throws IOException{
		StringBuffer sb = new StringBuffer() ; 
		InputStream is;
		NutMap resultMap =	NutMap.NEW();
		String str = "";
		try {
			is = request.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);   
			BufferedReader br = new BufferedReader(isr); 
			String s = "" ; 
			while((s=br.readLine())!=null){ 
				sb.append(s) ;  
			} 
			str =sb.toString();
			tenpaylog.info("[微信回调]："+str); 
			
			NutMap resMap = Xmls.xmlToMap(str);
			if(tenpayService.checkSign(resMap)){
				if("SUCCESS".equals(resMap.getString("return_code"))&&"SUCCESS".equals(resMap.getString("result_code"))){
					String out_trade_no = resMap.getString("out_trade_no");
					String openId = resMap.getString("openid");
					String transactionId = resMap.getString("transaction_id");
					//完成支付订单
					luckDrawService.finishedOrder(out_trade_no, openId, transactionId);
					resultMap.put("return_code", "SUCCESS");
					resultMap.put("return_msg", "OK");
				}else{
					resultMap.put("return_code", "SUCCESS");
					resultMap.put("return_msg", "OK");
					tenpaylog.info("参数格式校验错误："+str);
				}
			}else{
				resultMap.put("return_code", "FAIL");
				resultMap.put("return_msg", "验证签名失败");
				tenpaylog.info("验证签名失败,签名不一致,XML内容："+str);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("return_code", "FAIL");
			resultMap.put("return_msg", "析回调通知XML出错");
			tenpaylog.info("解析回调通知XML出错,XML内容："+str);
		}
		response.getWriter().write(Xmls.mapToXml(resultMap));
	}
	
}
